<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menuLeft">
        <!-- <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAddBtn()">新 增 </el-button> -->
      </template>
      <template slot-scope="{ row }" slot="menu">
        <!-- <el-button
          type="text"
          icon="el-icon-edit"
          size="small"
          plain
          :disabled="row.generationType == 'ERP' || row.status == 0"
          style="border: 0; background-color: transparent !important"
          @click.stop="handleEdit(row)"
          >编辑
        </el-button> -->
        <el-button
          type="text"
          size="small"
          icon="el-icon-delete"
          plain
          :disabled="row.status == 0 || row.status == 2"
          style="border: 0; background-color: transparent !important"
          @click="rowDel(row)"
          >删 除
        </el-button>
      </template>
    </avue-crud>
    <el-dialog append-to-body :close-on-click-modal="false" :title="title" :visible.sync="showDialog" v-if="showDialog" width="60%" top="7vh">
      <avue-form ref="properties" v-model="properties" :option="propertiesOption"></avue-form>
      <h3></h3>
      <avue-crud
        :option="sheetOption"
        :table-loading="detailLoading"
        :data="sheetData"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="sheetForm"
        ref="addTableCrud"
        @selection-change="selectionDetailChange"
      >
      </avue-crud>
      <span slot="footer" class="dialog-footer" :style="{ display: isNone }">
        <el-button v-if="title !== '详情'" type="primary" size="small" icon="el-icon-circle-plus-outline" @click="handleSubmit()" v-preventReClick>保存</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="showDialog = false">取 消</el-button>
      </span>
      <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    </el-dialog>

    <el-dialog append-to-body :close-on-click-modal="false" title="包装详情" :visible.sync="showPackDialog" v-if="showPackDialog" width="60%" top="7vh">
      <avue-form ref="properties" v-model="properties" :option="propertiesOption"></avue-form>
      <avue-crud
        @current-change="currentPackChange"
        @size-change="sizePackChange"
        @tree-load="treeLoad"
        :option="packOption"
        :page.sync="packPage"
        :table-loading="packLoading"
        :data="packData"
        v-model="packForm"
        ref="packTableCrud"
      >
      </avue-crud>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getDetail, getDetailTo, add, update, remove, getSheetPackInfo } from '@/api/warehouse/deliveryNote';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import userTableConfig from '@/components/user-table-config/index.vue';
export default {
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  // mixins: [userConfig()],
  data() {
    return {
      pageCode: 'DELIVERY_NOTE',
      form: {},
      typeObj: {},
      sheetForm: {},
      properties: {},
      timer: new Date().getTime(),
      loading: false,
      showPackDialog: false,
      packLoading: false,
      packData: [],
      packForm: {},
      packPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      allData: [],
      detailLoading: false,
      poDetailLoading: false,
      isNone: '', //是否显示修改
      status: '',
      tableOption: [], //模态框配置
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      rowData: {}, //行数据
      selectionList: [],
      selectionDetailList: [],
      selectionPoDetailList: [],
      showDialog: false,
      data: [],
      sheetData: [],
      sheetDetails: [],
      option: {
        calcHeight: 30,
        tip: false,
        dialogClickModal: false,
        border: true,
        height: 'calc(100vh - 406px)',
        viewBtn: false,
        addBtn: false,
        selection: false,
        printBtn: false,
        editBtn: false,
        delBtn: false,
        index: true,
        indexLabel: '序号',
        searchShow: true,
        searchMenuPosition: 'right',
        searchMenuSpan: 12,
        searchLabelWidth: 100,
        menu: false,
        menuWidth: 100,
        searchSpan: 5,
        columnBtn: false,
        column: [
          {
            label: '送货单号',
            prop: 'sheetNo',
            search: true,
            searchSpan: 6,
            searchOrder: 1,
            rules: [
              {
                required: true,
                message: '请输入送货单号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '行号',
            prop: 'sheetLot'
          },
          {
            label: '关联采购单号',
            prop: 'purchaseOrderNo',
            search: true,
            searchOrder: 2,
            searchSpan: 6,
            rules: [
              {
                required: true,
                message: '请输入关联采购单号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '供应商',
            prop: 'vendorName',
            search: true,
            searchSpan: 6,
            searchOrder: 3
          },
          {
            label: '物料品牌',
            prop: 'partBrand'
          },
          {
            label: '物料编码',
            prop: 'partNo',
            searchSpan: 6,
            search: true,
            searchOrder: 4
          },
          {
            label: '物料规格',
            prop: 'partModel',
            search: true,
            searchSpan: 6,
            searchOrder: 5
          },
          {
            label: '计划数量',
            prop: 'purchaseOrderQuantity'
          },
          {
            label: '收料数量',
            prop: 'receivingQuantity'
          },
          {
            label: '可收数量',
            prop: 'openQuantity'
          },
          {
            label: '单据状态',
            prop: 'status',
            search: true,
            searchOrder: 6,
            searchSpan: 6,
            type: 'select',
            dataType: 'string',
            dicData: [
              { label: '正常', value: '1' },
              { label: '完成', value: '2' },
              { label: '取消', value: '3' },
              { label: '关闭', value: '4' },
              { label: '收料中', value: '5' }
            ]
          },
          {
            label: '来源',
            prop: 'sourceType',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=sheet_source',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          }
        ]
      },
      propertiesOption: {
        //单据FORM配置
        labelWidth: '110',
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '送货单号',
            prop: 'sheetNo',
            disabled: true,
            rules: [
              {
                message: '系统自动生成',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '供应商',
            prop: 'vendorName',
            type: 'search',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择供应商',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openPartnerModal();
            }
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            disabled: false,
            display: true,
            dataType: 'string',
            dicData: [
              { label: '正常', value: '1' },
              { label: '完成', value: '2' },
              { label: '取消', value: '3' },
              { label: '关闭', value: '4' }
            ]
          },
          {
            label: '关联采购单号',
            prop: 'purchaseOrderNoStr',
            type: 'search',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择采购单号',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openPurchaseOrderModal();
            }
          }
        ]
      },
      sheetOption: {
        tip: false,
        searchShow: true,
        searchSpan: 4,
        searchMenuSpan: 6,
        dialogClickModal: false,
        height: '400',
        border: true,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        cancelBtn: false,
        saveBtn: false,
        selection: false,
        menu: false,
        page: false,
        index: false,
        indexLabel: '序号',
        refreshBtn: false,
        expandBtn: false,
        column: [
          {
            label: '采购单号',
            prop: 'purchaseOrderNo'
          },
          {
            label: '下单日期',
            prop: 'reservationArrivalTime'
          },
          {
            label: '单行号',
            prop: 'purchaseOrderLot'
          },
          {
            label: '物料编码',
            prop: 'partNo'
          },
          {
            label: '物料型号',
            prop: 'partModel'
          },
          {
            label: '采购数量',
            prop: 'quantity'
          },
          {
            label: '已入库数量',
            prop: 'storageQuantity'
          },
          {
            label: '已收数量',
            prop: 'receivingQuantity'
          },
          {
            label: '可收数量',
            prop: 'openQuantity'
          },
          {
            label: '单位',
            prop: 'uom'
          }
        ]
      },
      packOption: {
        tip: false,
        tree: true,
        lazy: true,
        expanded: true,
        expandRowKeys: [],
        searchShow: true,
        searchSpan: 4,
        searchMenuSpan: 6,
        dialogClickModal: false,
        height: '400',
        border: true,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        cancelBtn: false,
        saveBtn: false,
        selection: false,
        menu: false,
        page: true,
        index: false,
        refreshBtn: false,
        expandBtn: false,
        column: [
          {
            label: '序号',
            prop: 'dataIndex',
            fixed: true
          },
          {
            label: '包装层级',
            prop: 'level'
          },
          {
            label: '包装条码',
            prop: 'sequenceNumber'
          },
          {
            label: '采购数量',
            prop: 'quantity'
          },
          {
            label: '物料编码',
            prop: 'partMasterCode'
          },
          {
            label: '物料名称',
            prop: 'partMasterName'
          },
          {
            label: '物料规格',
            prop: 'partMasterModel'
          }
        ]
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.purchaseReturn_add, false),
        viewBtn: this.vaildData(this.permission.purchaseReturn_view, false),
        delBtn: this.vaildData(this.permission.purchaseReturn_delete, false),
        editBtn: this.vaildData(this.permission.purchaseReturn_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    currentPackChange(currentPage) {
      this.packPage.currentChange = currentPage;
      this.packData = this.allData.slice(currentPage * this.packPage.pageSize - 15, currentPage * this.packPage.pageSize);
    },
    sizePackChange(pageSize) {
      this.packPage.pageSize = pageSize;
      this.packData = this.allData.slice(0, pageSize);
    },
    treeLoad(tree, treeNode, resolve) {
      resolve(tree.children);
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.rdbPoId);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete(titleCrud) {
      if (titleCrud == 'sheetDel') {
        if (this.selectionList.length === 0) {
          this.$message.warning('请选择至少一条数据');
          return;
        }
        this.$confirm('确定将选择数据删除?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            return remove(this.rdbPoId);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.$refs.crud.toggleSelection();
          });
      }
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionDetailChange(list) {
      this.selectionDetailList = list;
    },
    selectionPoDetailChange(list) {
      this.selectionPoDetailList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query))
        .then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.selectionClear();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleSync() {},
    reset() {},
    /**
     * 新增模态框
     */
    handleAddBtn() {
      this.title = '新增';
      this.showDialog = true;
      this.resetData();
    },
    /**
     * 编辑模态框
     */
    handleEdit(row) {
      this.title = '编辑';
      this.showDialog = true;
      this.resetData();
      this.properties.sheetNo = row.sheetNo;
      this.properties.sourceNo = row.sourceNo;
      this.properties.status = row.status.toString();
      this.properties.partnerName = row.partnerName;
      this.properties.partnerId = row.partnerId;
      this.properties.partnerCode = row.partnerCode;
      this.getPurchaseReturnDetail(row.rdbId);
    },
    /*
     *采购退货详情
     */
    async getPurchaseReturnDetail(rdbPoId) {
      let result = await getDetail(rdbPoId);
      let sheetData = [];
      this._forEach(result.data.data, (item, index) => {
        sheetData.push({
          sheetType: item.sheetType,
          sheetNo: item.sheetNo,
          sheetLot: item.sheetLot,
          unitPrice: item.unitPrice,
          eventDate: item.eventDate,
          partMasterId: item.partMasterId,
          uom: item.uom,
          quantity: item.quantity,
          sourceCreateDate: item.eventDate,
          sheetHeaderId: item.sheetHeaderId,
          id: item.id,
          partNo: item.partNo,
          sourceId: item.sourceId,
          sourceNo: item.sourceNo,
          sourceType: item.sourceType,
          sourceDetailId: item.sourceDetailId,
          sourceLot: item.sourceLot,
          partMasterCode: item.partMasterCode,
          partMasterName: item.partMasterName,
          partMasterModel: item.partMasterModel,
          unitQty: item.unitQty,
          partnerName: item.partnerName,
          categoryName: item.categoryName,
          completedQuantity: item.completedQuantity,
          partnerId: item.partnerId
        });
      });
      this.sheetData = sheetData || [];
    },
    /**
     * 选择模态框数据
     */
    async getSelectedRows(rowData, titleInfo) {
      switch (titleInfo) {
        case 'purchaseOrderInfo':
          this.properties.purchaseOrderNoStr = [...new Set(rowData.map((item) => item.purchaseOrderNo))].join(',');
          this.sheetData = structuredClone(rowData);
          console.log(rowData, 'rowData');
          break;
        case 'vendorName':
          this.$set(this.properties, 'vendorName', rowData.name);
          this.$set(this.properties, 'vendorCode', rowData.partnerNo);
          this.$set(this.properties, 'vendorId', rowData.id);
          break;
        default:
          break;
      }
    },
    /*
     * 提交
     */
    handleSubmit() {
      this.$refs.properties.validate((valid, done) => {
        if (valid) {
          let params = {
            partnerId: this.properties.partnerId,
            partnerName: this.properties.partnerName,
            partnerCode: this.properties.partnerCode,
            sourceNo: this.properties.sourceNo,
            // sourceId: this.properties.sourceId,
            originalSheetId: this.properties.originalSheetId,
            status: this.properties.status,
            id: this.properties.id,
            sourceType: 'PO',
            generationType: 'MES',
            sheetSubType: 'GENERAL',
            sheetDetails: this.sheetData
          };
          add(params).then(
            (res) => {
              let data = res.data.data;
              this.$message({
                type: 'success',
                message: `${data.sheetNo}送货单${this.title === '新增' ? '新增' : '编辑'}成功!`
              });
              this.showDialog = false;
              this.resetData();
              this.refreshChange();
            },
            (error) => {
              window.console.log(error);
            }
          );
        }
      });
    },

    /**
     * 添加单据物料数据 PO
     */
    addTableData(data) {
      let tempArr = [];
      for (let i = 0; i < data.length; i++) {
        let item = {
          ...data[i],
          $cellEdit: true
        };
        this.title === '详情' && delete item.$cellEdit;
        tempArr.push(item);
      }
      return this._orderBy(tempArr, ['sheetLot'], ['asc']);
    },

    //数据重置
    resetData() {
      this.sheetData = [];
      this.sheetDetails = [];
      this.properties = {};
    },
    /**
     * 供应商信息模态框
     */
    openPartnerModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择供应商信息（双击进行选择）',
        url: '/api/mes-admin/vendor/page',
        isPage: true,
        index: false,
        rowSelectionType: 'single',
        titleInfo: 'vendorName',
        columnDefs: [
          {
            label: '编码',
            prop: 'code',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '缩写',
            prop: 'abbreviation'
          },
          {
            label: '联系人',
            prop: 'principal'
          },
          {
            label: '联系方式',
            prop: 'contacts'
          },
          {
            label: '位置',
            prop: 'locations'
          }
        ]
      };
    },
    /**
     * 采购单号模态框
     */
    openPurchaseOrderModal() {
      if (!this.properties.vendorName) {
        this.$message({
          type: 'warning',
          message: '请先选择供应商!'
        });
        return;
      }
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择采购单信息（双击进行选择）',
        url: `/api/mes-warehouse/purchase-order/page?vendorName=${this.properties.vendorName}`,
        isPage: true,
        index: false,
        rowSelectionType: 'multiple',
        titleInfo: 'purchaseOrderInfo',
        columnDefs: [
          {
            label: '采购单号',
            prop: 'purchaseOrderNo',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入采购单号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '行号',
            prop: 'purchaseOrderLot'
          },
          {
            label: '供应商名称',
            prop: 'vendorName'
          },
          {
            label: '物料编码',
            prop: 'partNo'
          },
          {
            label: '物料型号',
            prop: 'partModel'
          },
          {
            label: '单据状态',
            prop: 'status',
            search: true,
            type: 'select',
            dataType: 'string',
            dicData: [
              { label: '正常', value: '1' },
              { label: '完成', value: '2' },
              { label: '取消', value: '3' },
              { label: '关闭', value: '4' }
            ]
          }
        ]
      };
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  padding-top: 20px;
  justify-content: flex-end;
}

::v-deep .el-dialog .avue-crud__menu {
  display: none;
}
</style>
